import axios from 'axios'
import { env } from 'process'
import { getParamData } from './paramFa'
const transformResponse = function (res) {
	/* eslint-disable*/
	res = res.replace(/\"product_id\":(\d+)/g, '"product_id":"$1"')

	res = res.replace(/\"size_info_template_id\":(\d+)/g, '"size_info_template_id":"$1"')
	res = res.replace(/\"out_sku_id\":(\d+)/g, '"out_sku_id":"$1"')
	res = res.replace(/\"out_product_id\":(\d+)/g, '"out_product_id":"$1"')

	// LOG.info(res)
	return JSON.parse(res)
}
const service = axios.create({
	baseURL: env.BASE_URL,
	timeout: 200000,
	transformResponse
})
// http请求拦截
service.interceptors.request.use(
	async (config) => {
		const paramData = await getParamData(config)
		// console.log('config234', config)
		// console.log('paramData', paramData)
		if (!/\?/.test(config.url) && (config.method === 'get' || config.method === 'GET')) {
			let str = splitJoint(paramData)
			config.url += str
		}
		config.headers['Content-Type'] = 'application/json'
		if (config.method === 'post' || config.method === 'POST') {
			config.data = {
				...paramData,
				// ...config.data,
			}
			// console.log('config.data', config.data)
		}
		// console.log('config',config.url, config.method ,config.data)
		return config
	},
	(error) => {
		// console.log(error, '123456798***---32165489797')
		Promise.reject(error)
	}
)

function splitJoint(obj) {
	let arr = []
	for (let key in obj) {
		arr.push(key + '=' + obj[key])
	}
	return arr.length > 0 ? '?' + arr.join('&') : ''
}

// response 拦截器
service.interceptors.response.use(
	(response) => {
		// console.log('response',  response.data)
		return response.data
	},
	(error) => {
		// console.log('ererer', error, 'erroyer')
		return Promise.reject(error)
	}
)
export default service
